package com.egene.tw.activity.settings.devicelist;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.egene.tw.R;
import com.egene.tw.activity.signs.BaseMeasureActivity;
import com.egene.tw.activity.signs.heart.HeartActivity;
import com.egene.tw.base.BaseActivity;
import com.egene.tw.blue.BleEngine;
import com.egene.tw.blue.BluetoothLeServiceV2;
import com.egene.tw.blue.BtDevice;
import com.egene.tw.bus.BusHelper;
import com.egene.tw.data.RealmHelper;
import com.egene.tw.data.entity.BloodData;
import com.egene.tw.data.entity.HeartData;
import com.egene.tw.utils.PermissionUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.LongClick;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import io.realm.Realm;

@EActivity(R.layout.activity_device_list)
public class DeviceListActivity extends BaseMeasureActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusHelper.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusHelper.unRegister(this);
        stopScanBle();
    }

    //ToolBar Views
    @ViewById(R.id.actionBar)
    Toolbar mToolbarView;
    @ViewById(R.id.toolbar_title)
    TextView mToolBarTitle;


    @ViewById(R.id.textDevice)
    TextView textDevice;
    @ViewById(R.id.viewGou)
    View viewGou;
    @ViewById(R.id.viewSearch)
    View viewSearch;

    @ViewById(R.id.mRecyclerView)
    RecyclerView mRecyclerView;


    @AfterViews
    void initViews() {

        mToolbarView.setNavigationIcon(R.drawable.ic_back);
        mToolbarView.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initListView();
        initBle();

        loadCurrDevice();

        String address = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(address)) {
            scan1();
        }
    }

    @Click(R.id.viewSearch)
    public void viewSearch() {
        mDatas.clear();
        mAdapter.notifyDataSetChanged();
        addressSet.clear();

        scan1();
    }


    public void scan1() {
        if (checkBT()) {
            BluetoothLeServiceV2.scan(this);
        }
    }

    @LongClick(R.id.viewGou)
    public void viewGou() {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("確定解除綁定該手環嗎？")
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        RealmHelper.saveDeviceName(null);
                        RealmHelper.saveDeviceAddress(null);
                        loadCurrDevice();

                        BluetoothLeServiceV2.disconnect(DeviceListActivity.this);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }


    @Subscribe
    public void onEvent(BtDevice device) {
        if (addressSet.contains(device.getAddress())) {
            return;
        }
        addressSet.add(device.getAddress());
        mDatas.add(device);
        mAdapter.notifyDataSetChanged();
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case PermissionUtils.P_CODE_BLUE_TOOTH:
//                if (PermissionUtils.checkGrantResults(grantResults)) {
//                    checkPAndStart();
//                }
//                break;
//        }
//    }
//
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK) {
//            switch (requestCode) {
//                case PermissionUtils.P_CODE_BLUE_TOOTH:
//                    checkPAndStart();
//                    break;
//            }
//        }
//    }
//
//
//    private BleEngine bleEngine;
//
//    private void checkPAndStart() {
//        if (checkBT()) {
//            BluetoothLeServiceV2.checkPAndStart(this);
//        }
//    }
//
//    private void stopScanBle() {
//        BluetoothLeServiceV2.stopScan(this);
//    }
//
//
//    /**
//     * 检查蓝牙
//     */
//    private boolean checkBT() {
//        return checkBTPermission() && checkBTEnableAndOpen();
//    }
//
//
//    /**
//     * 检查是否有权限，若无，则请求权限
//     */
//    private boolean checkBTPermission() {
//        if (!PermissionUtils.checkHasPermission(this, PermissionUtils.PERMISSIONS_BLUE_TOOTH)) {
//            PermissionUtils.requestPermissions(this, PermissionUtils.PERMISSIONS_BLUE_TOOTH, PermissionUtils.P_CODE_BLUE_TOOTH);
//            return false;
//        }
//        return true;
//    }
//
//    public boolean checkBTEnable() {
//        return bleEngine.checkBTEnable();
//    }
//
//    /**
//     * 检查蓝牙功能是否打开，若未打开，则请求打开
//     */
//    private boolean checkBTEnableAndOpen() {
//        if (!checkBTEnable()) {
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enableBtIntent, PermissionUtils.P_CODE_BLUE_TOOTH);
//            return false;
//        }
//        return true;
//    }

    private void loadCurrDevice() {
        String name = RealmHelper.getDeviceName();
        String address = RealmHelper.getDeviceAddress();

        if (TextUtils.isEmpty(address)) {
            viewGou.setVisibility(View.GONE);
            viewSearch.setVisibility(View.VISIBLE);
        } else {
            textDevice.setText((TextUtils.isEmpty(name) ? "unknown" : name) + "\n" + address);
            viewGou.setVisibility(View.VISIBLE);
            viewSearch.setVisibility(View.GONE);
        }
    }


    private void connect(BtDevice btDevice) {
        RealmHelper.saveDeviceName(btDevice.getName());
        RealmHelper.saveDeviceAddress(btDevice.getAddress());

        loadCurrDevice();

        stopScanBle();

        BluetoothLeServiceV2.reconnect(this);
    }


    private HomeAdapter mAdapter;
    private List<BtDevice> mDatas;
    private Set<String> addressSet = new HashSet<>();

    private void initListView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDatas = new ArrayList<>();
        mAdapter = new HomeAdapter();
        mRecyclerView.setAdapter(mAdapter);
    }


    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> implements View.OnClickListener {

        @Override
        public HomeAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(DeviceListActivity.this).inflate(R.layout.item_device, parent, false);
            HomeAdapter.MyViewHolder holder = new HomeAdapter.MyViewHolder(view);

            view.setOnClickListener(this);
            return holder;
        }

        @Override
        public void onBindViewHolder(HomeAdapter.MyViewHolder holder, int position) {
            BtDevice item = mDatas.get(position);
            holder.textTitle.setText(TextUtils.isEmpty(item.getName()) ? "unknown" : item.getName());
            holder.textContent.setText(item.getAddress());

            holder.itemView.setTag(position);
        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }

        @Override
        public void onClick(View v) {
            final int pos = (int) v.getTag();
            if (mDatas.size() > pos) {
                new AlertDialog.Builder(DeviceListActivity.this)
                        .setTitle("提示")
                        .setMessage("確定綁定該手環嗎？")
                        .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                connect(mDatas.get(pos));
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView textTitle;
            TextView textContent;

            public MyViewHolder(View view) {
                super(view);
                textTitle = (TextView) view.findViewById(R.id.textTitle);
                textContent = (TextView) view.findViewById(R.id.textContent);
            }
        }
    }
}
